package com.tianbing.adlottery.controller.user;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.fengniu.ejb.dao.IUserDao;
import com.fengniu.ejb.entity.User;
import com.tianbing.adlottery.helper.WebSiteHttpClient;
import com.tianbing.adlottery.util.ControllerFormBean;
import com.tianbing.adlottery.util.EmailUtil;

public class EditPasswordForgetController extends SimpleFormController {
	static Logger logger = Logger.getLogger(EditPasswordForgetController.class.getName());

	private EmailUtil emailUtil;

	private IUserDao userDao;

	private String systemName;

	private String systemEmailAddr;

	private WebSiteHttpClient webSiteHttpClient;

	// ------------------GET Request LifeCycle------------------
	protected Object formBackingObject(HttpServletRequest request) throws Exception {
		// Person party = new Person();
		ControllerFormBean fb = new ControllerFormBean();
		// fb.setPerson(party);
		return fb;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
	 *      org.springframework.validation.BindException)
	 */
	protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object cmd,
			BindException ex) throws Exception {

		ModelAndView mv = new ModelAndView(this.getSuccessView());

		ControllerFormBean fb = (ControllerFormBean) cmd;
		String emailAddr = fb.getEmailAddr();
		User user = userDao.findUserByUserId(emailAddr);
		if (user != null) {
			String url = "http://localhost:8080/adweb/email/viewforgetpasswordemail.eml?usid=" + user.getSysId();

			String emailContent = webSiteHttpClient.getterCall(url);
			emailUtil.sendMessage(user.getNickName(), user.getUserId(), systemName, systemEmailAddr, "Your Password",
					null, emailContent);
			logger.info("email coupon:\n" + emailContent);
		}
		return mv;
	}

	public void setEmailUtil(EmailUtil emailUtil) {
		this.emailUtil = emailUtil;
	}

	public void setSystemEmailAddr(String systemEmailAddr) {
		this.systemEmailAddr = systemEmailAddr;
	}

	public void setSystemName(String systemName) {
		this.systemName = systemName;
	}

	public void setUserDao(IUserDao userDao) {
		this.userDao = userDao;
	}

	public static void setLogger(Logger logger) {
		EditPasswordForgetController.logger = logger;
	}

	public void setWebSiteHttpClient(WebSiteHttpClient webSiteHttpClient) {
		this.webSiteHttpClient = webSiteHttpClient;
	}

}
